package com.tianji.learning.handler;

import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.learning.domain.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.utils.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static com.tianji.learning.domain.constants.LearningConstants.POINTS_BOARD_TABLE_PREFIX;

@Component
@RequiredArgsConstructor
public class PointsBoardPersistentHandler {
    private final IPointsBoardService pointsBoardService;
    private final IPointsBoardSeasonService seasonService;
    private final StringRedisTemplate redisTemplate;

    @XxlJob("createTableJob")
    public void createPointsBoardTableOfLastSeason(){
        //1.获取上月时间
        LocalDate lastMonth = LocalDate.now().minusMonths(1);
        //2.查询赛季id
        Integer season =  seasonService.querySeasonIdByTime(lastMonth);
        if (ObjectUtils.isEmpty(season)){
            return;
        }
        //3.创建表
        pointsBoardService.createPointsBoardTableBySeason(season);
    }
    @XxlJob("savePointsBoard2DB")
    public void savePointsBoard2DB(){
        //1.获取上月时间
        LocalDate lastMonth = LocalDate.now().minusMonths(1);
        //2.计算动态表明
        //2.1查询赛季信息
        Integer season =  seasonService.querySeasonIdByTime(lastMonth);
        //2.2将表明存入ThreadLocal
        TableInfoContext.setInfo(POINTS_BOARD_TABLE_PREFIX + season);

        //3.查询榜单数据
        //3.1拼接key
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + lastMonth.format(DateUtils.POINTS_BOARD_SUFFIX_FORMATTER);
        //3.2查询寻数据
        int index = XxlJobHelper.getShardIndex();
        int total = XxlJobHelper.getShardTotal();
        int pageNo = 1 + index;
        int pageSize = 100;
        while (true){
            List<PointsBoard> boardList = pointsBoardService.queryCurrentBoardList(key, pageNo, pageSize);
            if(CollectionUtils.isEmpty(boardList)){
                break;
            }

            //4.持久化到数据库
            //4.1吧排名信息写入id
            for (PointsBoard b : boardList) {
                b.setId(b.getRank().longValue());
                b.setRank(null);
            }
            //4.2持久化
            pointsBoardService.saveBatch(boardList);
            //5.翻页
            pageNo+= total;
        }
        //删除ThreadLocal
        TableInfoContext.remove();
    }

    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis() throws InterruptedException {
        Thread.sleep(2000);
        // 1.获取上月时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);
        // 2.计算key
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + time.format(DateUtils.POINTS_BOARD_SUFFIX_FORMATTER);
        // 3.删除
        redisTemplate.unlink(key);
    }
}
